package com.yuaer.demo.springsparkjobrunnerdemo;


import com.alibaba.fastjson.JSON;
import com.yuaer.demo.springsparkjobrunnerdemo.runner.ScriptRunner;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author liyang
 */
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
@Slf4j
public class SpringSparkJobRunnerDemoApplication implements ApplicationRunner {

    @Autowired
    private List<ScriptRunner> scriptRunners;

    public static void main(String[] args) {
        SpringApplication app = new SpringApplication(SpringSparkJobRunnerDemoApplication.class);
        app.setWebApplicationType(WebApplicationType.NONE);  // 禁止 Web 环境（包括 Tomcat）
        app.run(args);
    }

    @Override
    public void run(ApplicationArguments args) throws Exception {

        log.info("执行命令:{}", JSON.toJSONString(args));

        List<String> nonOptionArgs = args.getNonOptionArgs(); // 读取第一个非 --key=value 的参数作为任务名

        if (nonOptionArgs.isEmpty()) {
            log.info("未指定任务名称:{}", scriptRunners.stream().map(r -> r.getTaskName()).collect(Collectors.toList()));
            System.exit(1);
        }
        String taskName = args.getNonOptionArgs().get(0);
        ScriptRunner runner = scriptRunners.stream()
                .filter(r -> r.getTaskName().equalsIgnoreCase(taskName))
                .findFirst()
                .orElseThrow(() -> new IllegalArgumentException("未找到任务:" + taskName));
        runner.runTask(args);

        System.exit(0);
    }
}
